package com.ruoyi.framework;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * MQTT演示控制器
 * 用于展示如何使用MqttListenerService发布MQTT消息
 */
@RestController
@RequestMapping("/mqtt")
public class MqttDemoController {

    @Autowired
    private MqttListenerService mqttListenerService;

    /**
     * 发布MQTT消息示例
     * @param topic 主题
     * @param message 消息内容
     * @param qos QoS级别（可选，默认为1）
     * @return 操作结果
     */
    @GetMapping("/publish")
    public String publishMessage(
            @RequestParam String topic,
            @RequestParam String message,
            @RequestParam(required = false, defaultValue = "1") int qos) {
        try {
            mqttListenerService.publish(topic, message, qos);
            return "消息发布成功：主题=" + topic + ", 内容=" + message + ", QoS=" + qos;
        } catch (Exception e) {
            return "消息发布失败：" + e.getMessage();
        }
    }

    /**
     * 测试设备数据发布
     * @param deviceId 设备ID
     * @param data 设备数据
     * @return 操作结果
     */
    @GetMapping("/publish/device")
    public String publishDeviceData(
            @RequestParam String deviceId,
            @RequestParam String data) {
        String topic = "device/data/" + deviceId;
        return publishMessage(topic, data, 1);
    }

    /**
     * 测试用户命令发布
     * @param userId 用户ID
     * @param command 命令内容
     * @return 操作结果
     */
    @GetMapping("/publish/command")
    public String publishUserCommand(
            @RequestParam String userId,
            @RequestParam String command) {
        String topic = "user/command/" + userId;
        return publishMessage(topic, command, 1);
    }
}